#!/usr/bin/env python3
#
#   simple WSGI/Python based CMS script
#   commandline interface
#
#   Copyright (C) 2012 Michael Buesch <m@bues.ch>
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.

import sys
import getopt


def usage():
	print("Usage: %s [OPTIONS] [ACTION]" % sys.argv[0])
	print("")
	print("Options:")
	print("  -d|--db PATH           Path to database. Default: ./db")
	print("  -w|--www PATH          Path to the static data. Default: ./www-data")
	print("  -i|--images SUBPATH    Path to images. Default: /images")
	print("  -D|--domain DOMAIN     The domain name. Default: example.com")
	print("  -C|--cython            Import Cython modules")
	print("  -P|--profile LEVEL     Enable profiling")
	print("  -L|--loop LOOPS        Run LOOPS number of loops. For profiling.")
	print("")
	print("Actions:")
	print("  GET <path>             Do a GET request on 'path'")
	print("  POST <path>            Do a POST request on 'path'")

def main():
	action = None
	path = "/"
	opt_db = "./db"
	opt_www = "./www-data"
	opt_images = "/images"
	opt_domain = "example.com"
	opt_cython = False
	opt_profile = 0
	opt_loop = 1

	try:
		(opts, args) = getopt.getopt(sys.argv[1:],
			"hd:w:i:D:CP:L:",
			[ "help", "db=", "www=", "images=", "domain=", "cython",
			  "profile=", "loop=", ])
	except (getopt.GetoptError) as e:
		usage()
		return 1
	for (o, v) in opts:
		if o in ("-h", "--help"):
			usage()
			return 0
		if o in ("-d", "--db"):
			opt_db = v
		if o in ("-w", "--www"):
			opt_www = v
		if o in ("-i", "--images"):
			opt_images = v
		if o in ("-D", "--domain"):
			opt_domain = v
		if o in ("-C", "--cython"):
			opt_cython = True
		if o in ("-P", "--profile"):
			try:
				opt_profile = int(v)
			except ValueError:
				print("Invalid -P|--profile value")
				return 1
		if o in ("-L", "--loop"):
			try:
				opt_loop = int(v)
				if opt_loop < 1:
					raise ValueError
			except ValueError:
				print("Invalid -L|--loop value")
				return 1
	if len(args) >= 1:
		action = args[0]
	if len(args) >= 2:
		path = args[1]
	if not action:
		print("No action specified")
		return 1
	retval = 0
	cms = prof = None

	if opt_cython:
		from cms_cython import CMS, CMSException
		from cms_cython.profiler import Profiler
	else:
		from cms import CMS, CMSException
		from cms.profiler import Profiler
	try:
		if opt_profile >= 1:
			prof = Profiler()
			if opt_profile >= 2:
				prof.start()

		cms = CMS(dbPath=opt_db,
			  wwwPath=opt_www,
			  imagesDir=opt_images,
			  domain=opt_domain,
			  debug=True)

		if opt_profile == 1:
			prof.start()

		for _ in range(opt_loop):
			if action.upper() == "GET":
				data, mime = cms.get(path)
			elif action.upper() == "POST":
				data, mime = cms.post(path)
			else:
				print("Invalid action")
				return 1
		cms.shutdown()

		if opt_profile >= 1:
			prof.stop()

	except (CMSException) as e:
		if cms:
			data, mime, headers = cms.getErrorPage(e)
		else:
			data, mime = "CMSException", "application/xhtml+xml"
		retval = 1
	if "html" in mime:
		result = data + b"\n"
	else:
		result = data
	sys.stdout.buffer.write(result)
	sys.stdout.buffer.flush()
	if prof:
		print(prof.getResult(), file=sys.stderr)
	return retval

if __name__ == "__main__":
	sys.exit(main())
